//
//  BESerializeExtension.swift
//  BasicExtensions
//
//  Created by 范晓鑫 on 2022/12/12.
//

import Foundation

extension Encodable {
    public func serialize() throws -> Data {
        return try JSONEncoder().encode(self)
    }
}
extension Decodable {
    public static func deserialize(_ data: Data) throws -> Self {
        return try JSONDecoder().decode(Self.self, from: data)
    }
}
extension NSCoding {
    public func serialize() throws -> Data {
        if #available(iOS 11.0, *) {
            return try NSKeyedArchiver.archivedData(withRootObject: self, requiringSecureCoding: false)
        } else {
            return NSKeyedArchiver.archivedData(withRootObject: self)
        }
    }
    public static func deserialize(_ data: Data) throws -> Self {
        if let object = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data),
           let instance = object as? Self {
            return instance
        } else {
           throw NSError(info: "反序列化失败")
        }
    }
}

extension BEElementSerializable {
    /// 从Data反序列化元素
    public func element(for data: Data) throws -> Element {
        if let T = Element.self as? BESerializable.Type {
            return try T.deserialize(data) as! Element
        } else if let T = Element.self as? Codable.Type {
            return try T.deserialize(data) as! Element
        } else if let T = Element.self as? NSCoding.Type {
            return try T.deserialize(data) as! Element
        }
        throw NSError(info: "unsupported")
    }
    /// 将元素序列化成Data
    public func data(for element: Element) throws -> Data {
        if let t = element as? BESerializable {
            return try t.serialize()
        } else if let t = element as? Codable {
            return try t.serialize()
        } else if let t = element as? NSCoding {
            return try t.serialize()
        }
        throw NSError(info: "unsupported")
    }
}
